import cx_Oracle
import os

# 数据库连接信息
dsn = cx_Oracle.makedsn('host', 'port', service_name='service_name')
connection = cx_Oracle.connect(user='your_username', password='your_password', dsn=dsn)
cursor = connection.cursor()

username = 'TARGET_SCHEMA_NAME'  # 替换为你需要导出的用户
output_dir = username  # 创建以用户名命名的文件夹

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 查询当前用户下所有表名
cursor.execute(f"SELECT table_name FROM all_tables WHERE owner = '{username}'")

tables = cursor.fetchall()
for table in tables:
    table_name = table[0]
    print(f"Exporting structure for {table_name}...")

    # 获取建表语句
    cursor.execute(f"""
        SELECT DBMS_METADATA.GET_DDL('TABLE', '{table_name}', '{username}') FROM dual
    """)
    ddl, = cursor.fetchone()

    # 写入文件
    with open(os.path.join(output_dir, f"{table_name}.sql"), 'w') as f:
        f.write(ddl.read())

print("导出完成！")
cursor.close()
connection.close()
